import { defineStore } from 'pinia';
import { computed, onMounted, ref, watch } from 'vue';
import useStorage from '@/composables/useStorage.ts';
import { getCustomCookie, setCustomCookie } from '@/utils/common.ts';
import { APPEARANCE_KEY } from '@/config/common.ts';
import { isClient } from '@opensig/opendesign';
import { inBrowser } from 'vitepress';

/**
 * 页面状态
 */
export const useViewStore = defineStore('view', {
  state: () => {
    return {
      notFoundPage: false,
      noPermission: false,
    };
  },
  actions: {
    showNotFound() {
      this.notFoundPage = true;
    },
  },
});

export const useCookieStore = defineStore('cookie', {
  state: () => {
    return {
      status: '0',
      isNoticeVisible: false,
    };
  },
  getters: {
    isAllAgreed: (state) => state.status === '1',
  },
});

/**
 * 搜索状态
 */
export const useSearchingStore = defineStore('isSearching', {
  state: () => {
    return {
      isSearching: false,
      keyword: '',
      isLoading: false,
      currentPage: 1,
    };
  },
  actions: {
    setIsSearching(value: boolean) {
      this.isSearching = value;
    },
    setKeyword(value: string) {
      this.keyword = value;
    },
    setIsLoading(value: boolean) {
      this.isLoading = value;
    },
    setCurrentPage(value: number) {
      this.currentPage = value;
    },
  },
});

/**
 * 搜索历史
 */
export const useSearchHistoryStore = defineStore('search', () => {
  const searchHistoryStorage = useStorage('search-history', []);

  const add = (val: string) => {
    searchHistoryStorage.setValue([...new Set([val, ...searchHistoryStorage.value.value])]);
  };

  const remove = (val?: string) => {
    if (val) {
      searchHistoryStorage.setValue(searchHistoryStorage.value.value.filter((item) => item !== val));
    } else {
      clear();
    }
  };

  const clear = () => {
    searchHistoryStorage.setValue();
  };

  const list = computed(() => searchHistoryStorage.value.value.slice(0, 6));

  return { list, add, remove, clear };
});
export const useThemeStore = defineStore('theme', () => {
  const theme = ref<'light' | 'dark'>('light');
  const setTheme = (val) => {
    theme.value = val;
    setCustomCookie(APPEARANCE_KEY, val, 180);
  };

  onMounted(() => {
    let current = getCustomCookie(APPEARANCE_KEY);
    if (!current) {
      const preferDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      current = preferDark ? 'dark' : 'light';
    }
    theme.value = current === 'dark' ? 'dark' : 'light';
  });

  watch(
    () => theme.value,
    (val) => {
      if (isClient) {
        const documentElement = document.documentElement;
        if (val === 'light') {
          documentElement.removeAttribute('data-o-theme');
          documentElement.classList.remove('dark');
        }
        if (val === 'dark') {
          documentElement.setAttribute('data-o-theme', 'dark');
          documentElement.classList.add('dark');
        }
      }
    },
    { immediate: true },
  );

  return {
    theme,
    setTheme,
  };
});

export const useCommonStore = defineStore('common', () => {
  const closeFeedbackTip = ref(false);

  const setCloseFeedbackTip = () => {
    closeFeedbackTip.value = true;
  };

  const toggleBodyScroll = (flag: boolean) => {
    if (!inBrowser) {
      return;
    }
    const bodyEl = document.querySelector('body');
    bodyEl?.setAttribute('style', flag ? 'overflow: hidden;' : '');
  };

  const showMobileNav = ref(false);
  const toggleMobileNav = () => {
    showMobileNav.value = !showMobileNav.value;
    toggleBodyScroll(showMobileNav.value);
  };
  // -------------------- 登录弹窗 --------------------
  const loginDialogVisible = ref(false);
  const setLoginDialogVisible = (val: boolean) => {
    loginDialogVisible.value = val;
  };
  return {
    closeFeedbackTip,
    setCloseFeedbackTip,
    showMobileNav,
    toggleMobileNav,
    loginDialogVisible,
    setLoginDialogVisible,
  };
});
export const useHeaderStore = defineStore('header', () => {
  const tagMap = ref({});

  const updateTagMap = (map) => {
    tagMap.value = {
      ...tagMap.value,
      ...(map || {}),
    };
  };

  return {
    tagMap,
    updateTagMap,
  };
});
